import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import type { AsyncThunk, ActionReducerMapBuilder, PayloadAction, Slice } from '@reduxjs/toolkit'
import { getList, type GetListParams } from './totalUserAPI'
import { DataType } from "@/pages/TotalUser/Table";
import { TZ } from "@/utils/env";
import dayjs from '@/utils/dayjs'
import { v4 } from "uuid";

const threeDaysAgoStart = dayjs().tz(TZ).subtract(3, 'day').unix();
const todayEnd = dayjs().tz(TZ).unix();

interface InitialState {
  params: GetListParams,
  table: {
    status: 'init' | 'loading' | 'success' | 'error',
    data: Res | undefined,
    params?: GetListParams
  }
}

const initialState: InitialState = {
  params: {
    page: 1,
    page_size: 10,
    start_t: threeDaysAgoStart,
    end_t: todayEnd,
    channel: '',
    query_user_id: "",
    username: "",
    country: ""
  },
  table: {
    status: "init",
    data: undefined,
  }
};

type Res = {
  data: {
    total: number,
    page: number,
    page_data: DataType[]
  }
}
type AsyncRes = {
  data: Res,
  params: GetListParams
}
export const getListAsync: AsyncThunk<AsyncRes, GetListParams, {}> = createAsyncThunk<AsyncRes, GetListParams, {}>(
  "totalUser/getListAsync",
  async (params) => {
    const res: Res = await getList(params);
    return {
      data: res,
      params
    };
  }
);
const tableStatus: (builder: ActionReducerMapBuilder<InitialState>) => void = (builder: ActionReducerMapBuilder<InitialState>): void => {
  builder
    .addCase(getListAsync.pending, (state: InitialState): void => {
      state.table.status = "loading";
    })
    .addCase(getListAsync.fulfilled, (state: InitialState, action: PayloadAction<AsyncRes>): void => {
      state.table.status = "success";
      if(Array.isArray(action.payload?.data?.data?.page_data)){
        action.payload.data.data.page_data.forEach(i => i.uuid = v4())
      }
      state.table.data = action.payload.data;
      state.table.params = action.payload.params
    })
    .addCase(getListAsync.rejected, (state: InitialState): void => {
      state.table.status = "error";
    });
};

type Reducers = {
  changeParams: (state: InitialState, action: PayloadAction<Partial<GetListParams>>) => void
}
type Selectors = {}
const totalUserSlice: Slice<InitialState, Reducers, 'totalUser', 'totalUser', Selectors> = createSlice<InitialState, Reducers, 'totalUser', Selectors, 'totalUser'>({
  name: "totalUser",
  initialState,
  reducers: {
    changeParams(state: InitialState, action: PayloadAction<Partial<GetListParams>>): void {
      state.params = {
        ...state.params,
        ...action.payload,
      };
    }
  },
  extraReducers(builder: ActionReducerMapBuilder<InitialState>): void {
    tableStatus(builder);
  },
});

export const { changeParams }: typeof totalUserSlice.actions = totalUserSlice.actions;

export default totalUserSlice.reducer;
